const Router = require('koa-router')
const router = new Router({
    prefix: '/blog/art'
});


const { Article } = require('../../models/blog/article');
const Sequelize = require('sequelize')

//增加新的文章 
router.post('/add', async (ctx, next) => {
    const body = ctx.request.body;
    const res = await Article.create(body)
    ctx.body = {
        data: res,
        msg: 'ok'
    }
})
//查询所有文章
router.post('/', async (ctx, next) => {
    const body = ctx.request.body;
    const limit = body.limit || 10;
    const page = body.page || 1;
    const offset = (page - 1) * limit;
    const { keywords, class_id, tag } = ctx.request.body;

    const where = {
        tags: {
            [Sequelize.Op.like]: '%' + tag + '%'
        },
        name: {
            [Sequelize.Op.like]: '%' + keywords + '%'
        }
    }

    if(class_id){
        where.class_id = class_id;
    }
    
    const res = await Article.findAndCountAll({
        where,
        limit,
        offset
    })

    ctx.body = {
        data: res,
        msg: 'ok'
    }
})
//删除文章
router.post('/delete', async (ctx, next) => {
    const res = await Article.findAll({ where: {} })
    ctx.body = {
        data: res,
        msg: 'ok'
    }
})
//根据ID查找文章
router.post('/find', async (ctx, next) => {
    const res = await Article.findAll({ where: {} })
    ctx.body = {
        data: res,
        msg: 'ok'
    }
})

module.exports = router;